<?php

function sparkline($s1, $s2, $indent = null) {
	
	$output  = "<script type='text/javascript'>\n";
	$output .= "  $(document).ready(function() {\n";
	$output .= "    $('#". $s1 ."-". $s2 ."').sparkline('html', { fillColor: false })\n";

	$symbols = array($s1, $s2);

	foreach ($symbols as $symbol) {

		$query = sprintf("
			SELECT adj_close 
			FROM stock_data
			WHERE symbol = '%s'
			ORDER BY date DESC
			LIMIT 30",
			mysql_real_escape_string($symbol));

		$result = mysql_query($query);

		$values = array();

		while ($row = mysql_fetch_assoc($result)) {

			$values[] = $row["adj_close"];
		}

		$values = array_reverse($values);

		$output .= "    $('#". $s1 ."-". $s2 ."').sparkline([";

		foreach ($values as $value) {
			
			$output .= $value . ",";
		}

		$output = substr($output, 0, $output - 1);
		$output .= "], { composite: true, fillColor: false, lineColor: '" . (($symbol == $s1) ? "red" : "blue") ."' });\n";
	}

	$output .= "  });\n";
	$output .= "</script>\n";
	$output .= "<span id=\"". $s1 ."-". $s2 ."\"></span>\n";

	return indent($output, $indent);
}

function indent($string, $spaces) {
	//$string = str_pad($string, $spaces, " ", STR_PAD_LEFT);
	$pad = str_pad("", $spaces, " ", STR_PAD_LEFT);
	$string = str_replace("\n", "\n" . $pad, $string);
	return substr($string, 0, strlen($string) - $spaces);
}